package com.tanjie.blackbean.auth.granter;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import com.tanjie.blackbean.cache.repositories.UserInfoCache;
import com.tanjie.blackbean.cache.repositories.UserInfoCacheRepository;
import com.tanjie.blackbean.pojo.auth.UserInfoWithRolesAndPerms;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @author: tanjie
 * @date: 2022-04-24
 **/
@Slf4j
public abstract class AbstractTokenGranter implements ITokenGranter {

    @Resource
    UserInfoCacheRepository userInfoCacheRepository;

    public AbstractTokenGranter() {
        log.info("加载{}实现类", grantType());
        GranterHolder.put(grantType(), this);
    }

    void saveToCache(UserInfoWithRolesAndPerms userInfo, Date expiresIn) {
        UserInfoCache cache = BeanUtil.copyProperties(userInfo, UserInfoCache.class);
        cache.setCreateTimestamp(System.currentTimeMillis());
        cache.setCreateTimeStr(DateUtil.now());
        cache.setExpiresIn(expiresIn.getTime());
        cache.setExpiresInStr(DateUtil.formatDateTime(expiresIn));
        userInfoCacheRepository.save(cache);
    }

}
